#include "highgui.h"
#include "cv.h"
#include <stdio.h>
#include "ball.h"
#include "time.h"
#include "bar.h"
#include "motiontracking.h"
#include "sapi.h"
IplImage *frame;
IplImage* infoFrame;
bar b1,b2;
using namespace std;
double fpsvalue=0;
int counter = 0;
double sec = 0;

int main() {
	ISpVoice * pVoice = NULL;
	

    time_t start, end;
	string s;
	char key = 0;
	char *fps = new char[10];
	char *lives1 = new char[20];
	char *lives2 = new char[20];
	int a,b;
	boolean finished=false;
	CvCapture *capture;
 	capture = cvCreateCameraCapture(0);
	int y=0;
	// Check if the capture is ok
    if (!capture)
    {
		printf("Can't initialize the video capture.\n");
        return -1;
 	}
    
 	infoFrame = cvQueryFrame(capture); //First frame for informations
	motiontracking motion1(infoFrame);
	motiontracking motion2(infoFrame);
	b2.x = infoFrame->width-10;
	ball ball(infoFrame->width, infoFrame->height);
	cvNamedWindow( "output", 1 );
	
	//time started
	time(&start);
	
	while ((1)&&(!finished)){
		key = cvWaitKey(10);
		if( key == 27 )
            break;
		// First frame
		frame = cvQueryFrame(capture);
		time(&end); //time ended
		
		//fps calculations
		++counter;
		sec = difftime (end, start);   
        fpsvalue = counter / sec; 
		
		cvFlip(frame, NULL, 1); //mirror image
		
		//Print fps  scores on screen
		sprintf(fps,"FPS: %.2f", fpsvalue);
		cvPutText(frame, fps, cvPoint(20, 460), &cvFont(2,2), CV_RGB(0, 0, 0));
		

		

		a = motion1.calculatePositionY(frame,b1);
		b1.y += a;
		b = motion2.calculatePositionY(frame,b2);
		b2.y += b;
		

		b1.draw(frame);
		b1.checkCollision(ball);
		b2.draw(frame);	
		b2.checkCollision(ball);

		sprintf(lives1,"Lives : %d", b1.lives);
		sprintf(lives2,"Lives: %d", b2.lives);
		
		cvPutText(frame, lives1, cvPoint(20, 20), &cvFont(1), CV_RGB(0, 0, 0));
		cvPutText(frame, lives2, cvPoint(b2.x-70, 20), &cvFont(1), CV_RGB(0, 0, 0));

		ball.updatePositionandDraw(frame);
		
		if (b1.lives==0){
		cvPutText(frame,"Game Over! Right Side Wins", cvPoint(20,240), &cvFont(2),CV_RGB(0,0,0));
			finished=true;
		}
		
		else if (b2.lives==0) {
				cvPutText(frame,"Game Over! Left Side Wins", cvPoint(20,240),  &cvFont(2),CV_RGB(0,0,0));
				finished=true;
		
		}
		cvShowImage("output",frame);
		
		if (finished==true){
			char c = cvWaitKey();
			if (c=='r'){
				b1.lives=10;
				b2.lives=10;
				ball.init(frame->width/2, frame->height/2, rand() % 360);
				
				finished=false;
			}
			else
				break;
		}

	}

	// Destroy objects
	cvDestroyWindow("output");
	cvReleaseCapture(&capture);

	return 0;

}
